package com.icinfo.cloud.provider.common.zzd.service.impl;

import cn.hutool.http.HttpStatus;
import com.alibaba.fastjson.JSONObject;
import com.icinfo.cloud.common.core.config.RedisRepository;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.utils.BaseUtil;
import com.icinfo.cloud.provider.common.zzd.ZwddUtil;
import com.icinfo.cloud.provider.common.zzd.dto.AccessTokenInfo;
import com.icinfo.cloud.provider.common.zzd.dto.OperateDto;
import com.icinfo.cloud.provider.common.zzd.dto.ZzdUserInfo;
import com.icinfo.cloud.provider.common.zzd.service.IZzdUserLoginService;
import com.icinfo.cloud.provider.punish.dto.ZwdLoginRequest;
import com.icinfo.cloud.provider.punish.service.IXzzfInterfaceService;
import com.icinfo.framework.common.web.Result;
import com.icinfo.framework.tools.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;

/**
 * 描述：浙政钉登录接口
 *
 * @Author zhengqiang
 * @Date 2022/12/8 22:46
 **/
@Slf4j
@Service
public class ZzdUserLoginServiceImpl implements IZzdUserLoginService {

    public static final String ZZD_ACCESS_TOKEN_KEY = "ZJZLZF:ACCESS_TOKEN";

    public static final String GET_ACCESS_TOKEN ="getAccessToken";

    public static final String GET_ZW_DING_DING_USER ="getZWDingdingUser";

    @Resource
    private IXzzfInterfaceService xzzfInterfaceService;
    @Resource
    private RedisRepository redisRepository;
    @Value("${zzd.sendUrl}")
    private String dingSendUrl;
    @Value("${isPrd}")
    private String isPrd;


    /**
     * 一键登录
     * @author zhengqiang
     * @date 2022/12/8
     * @param zwdLoginRequest
     * @return {@link JSONObject}
     */
    @Override
    public Result zzdLogin(ZwdLoginRequest zwdLoginRequest) {
        String accessToken = redisRepository.get(ZZD_ACCESS_TOKEN_KEY);
        log.info("从redis中获取accessToken:" + accessToken);
        if (ObjectUtils.isEmpty(accessToken)) {
            AccessTokenInfo accessTokenInfo = new AccessTokenInfo();
            if ("true".equals(isPrd)) { //正式环境调用转发服务
                //调用转发服务
                OperateDto operateDto = new OperateDto();
                operateDto.setOperateType(GET_ACCESS_TOKEN);
                JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(operateDto));
                String response = BaseUtil.post(dingSendUrl, jsonObject);
                if (ObjectUtils.isEmpty(response)) {
                    return Result.error("调用服务异常");
                }
                Result accessToken1 = JSONObject.parseObject(response, Result.class);
                if (HttpStatus.HTTP_OK != accessToken1.getCode()) {
                    return Result.error(accessToken1.getMessage());
                }
                accessTokenInfo = JSONObject.parseObject(accessToken1.getData().toString(), AccessTokenInfo.class);
            } else {
                Result<AccessTokenInfo> accessToken1 = ZwddUtil.getAccessTokenNew();
                if (HttpStatus.HTTP_OK != accessToken1.getCode()) {
                    return Result.error(accessToken1.getMessage());
                }
                accessTokenInfo = accessToken1.getData();
            }

            accessToken = accessTokenInfo.getAccessToken();
            Integer expiresIn = Integer.valueOf(accessTokenInfo.getExpiresIn()) - 1000;
            redisRepository.setExpire(ZZD_ACCESS_TOKEN_KEY, accessToken, expiresIn);
        }
        log.info("获取到accessToken:" + accessToken);

        ZzdUserInfo user = new ZzdUserInfo();
        if ("true".equals(isPrd)) { //正式环境调用转发服务
            OperateDto operateDto = new OperateDto();
            operateDto.setOperateType(GET_ZW_DING_DING_USER);
            operateDto.setAccessToken(accessToken);
            operateDto.setAuthCode(zwdLoginRequest.getAuthCode());
            JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(operateDto));
            String userResponse = BaseUtil.post(dingSendUrl, jsonObject);
            if (ObjectUtils.isEmpty(userResponse)) {
                return Result.error("调用服务异常");
            }
            Result zwDingdingUser = JSONObject.parseObject(userResponse, Result.class);
            if (HttpStatus.HTTP_OK != zwDingdingUser.getCode()) {
                return zwDingdingUser;
            }
            user = JSONObject.parseObject(zwDingdingUser.getData().toString(), ZzdUserInfo.class);
        } else {
            Result<ZzdUserInfo> zwDingdingUser = ZwddUtil.getZWDingdingUser(accessToken, zwdLoginRequest.getAuthCode());
            if (HttpStatus.HTTP_OK != zwDingdingUser.getCode()) {
                return zwDingdingUser;
            }
            user = zwDingdingUser.getData();
        }

        String xzzfToken = xzzfInterfaceService.getXzzfTokenByAccountId("" + user.getAccountId());
        log.info("调用执法平台接口获取用户token:" + xzzfToken);
        if (ObjectUtils.isEmpty(xzzfToken)) {
            return Result.error("登录失败：未获取到用户信息");
        }
        user.setNewSystemToken(xzzfToken);
        return Result.success(Constant.STRING_SUCCESS_EN, user);

    }

    /**
     * 浙政钉获取用户信息
     *
     * @return ZzdUserInfo
     * @author huanghc
     * @date 2021-08-13
     */
    public Result<ZzdUserInfo> getZzdUserInfo(String code) {
        if (StringUtils.isBlank(code)) {
            log.error("获取政务钉钉授权码code为空");
            return null;
        }
        Result<AccessTokenInfo> accessToken = ZwddUtil.getAccessTokenNew();

        if (Result.DEFAULT_ERROR == accessToken.getCode()){
            log.error("getAccessToken（）失败");
            return Result.error(accessToken.getMessage());
        }
        final Result<ZzdUserInfo> userInfoByQrCode = ZwddUtil.getUserInfoByQrCode(accessToken.getData().getAccessToken(), code);
        if (Result.DEFAULT_ERROR == userInfoByQrCode.getCode()){
            log.error("getUserInfoByQrCode失败");
            return Result.error(userInfoByQrCode.getMessage());
        }
        ZzdUserInfo zzdUserInfo = new ZzdUserInfo();
        BeanUtils.copyProperties(userInfoByQrCode.getData(), zzdUserInfo);
        return Result.success(zzdUserInfo);
    }
}
